<template>
  <div>
    <SchemaForm
      ref="schemaFormRef"
      v-bind="{ ...getFormProps }"
      class="bg-white dark:bg-#212332 mb-16px"
    >
    </SchemaForm>
    <a-tabs type="card" class="h-full w-full">
      <a-tab-pane key="1" tab="菜单权限" forceRender>
        <a-form layout="horizontal" :labelCol="{ span: 4 }">
          <a-form-item label="菜单权限">
            <a-row class="mt-5px">
              <a-col :span="6"
                ><a-checkbox v-model:checked="menuStates.toggle">展开/折叠</a-checkbox></a-col
              >
              <a-col :span="6"
                ><a-checkbox v-model:checked="menuStates.selectedAll"
                  >全选/全不选</a-checkbox
                ></a-col
              >
            </a-row>
            <Tree
              class="mt-5px"
              checkable
              v-model:checkedKeys="menuStates.checkedKeys"
              v-model:expandedKeys="menuStates.expandedKeys"
              auto-expand-parent
              :selectable="false"
              :tree-data="defaultData.menusAll"
            >
            </Tree>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="数据权限" forceRender>
        <a-form layout="horizontal" :labelCol="{ span: 4 }">
          <a-form-item label="权限范围">
            <a-select v-model:value="persState.dataScope">
              <a-select-option value="1">全部数据权限</a-select-option>
              <a-select-option value="2">自定义数据权限</a-select-option>
              <a-select-option value="3">本部门数据权限</a-select-option>
              <a-select-option value="4">本部门及以下数据权限</a-select-option>
              <a-select-option value="5">仅本人数据权限</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="数据权限" v-if="persState.dataScope == '2'">
            <a-row class="mt-5px">
              <a-col :span="6"
                ><a-checkbox v-model:checked="deptsStates.toggle">展开/折叠</a-checkbox></a-col
              >
              <a-col :span="6"
                ><a-checkbox v-model:checked="deptsStates.selectedAll"
                  >全选/全不选</a-checkbox
                ></a-col
              >
            </a-row>
            <Tree
              class="mt-5px"
              checkable
              v-model:checkedKeys="deptsStates.checkedKeys"
              v-model:expandedKeys="deptsStates.expandedKeys"
              auto-expand-parent
              :selectable="false"
              :tree-data="defaultData.deptsAll"
            >
            </Tree>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="3" tab="成员列表" forceRender>
        <a-button type="primary" @click="openModal"> 新增 </a-button>
        <DynamicTable :dataSource="defaultData.users" :columns="columns" />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="tsx" setup>
  import { getRoleListPage } from '@/api/organization/roles/roles';
  import { useTable } from '@/components/core/dynamic-table';
  import { onMounted, reactive,h, ref, watch,unref, defineComponent } from 'vue';
  import { Tag, Tree } from 'ant-design-vue';
  import { SchemaForm } from '@/components/core/schema-form';
  import { useRoleSchema } from './formSchema';
  import { useModal } from '@/hooks/useModal/useModal';
  import userMore from '@/components/system/orgUserMore/userMore.vue';
  import { message, type FormInstance } from 'ant-design-vue';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    FileSyncOutlined,
  } from '@ant-design/icons-vue';

  interface Props {
    defaultData?: any;
  }
  defineComponent({
    userMore
  })

  const [ModalRender, modalRef] = useModal();

  const props = withDefaults(defineProps<Props>(), {
    defaultData: {
      roleData: {},
      menus: [],
      depts: [],
      users: [],
      menusAll: [],
      menuKeysAll: [],
      deptsAll: [],
      deptsKeysAll: [],
    },
  });

  defineOptions({
    name: 'RoleAuth',
  });

  const deptsStates = reactive({
    checkedKeys: [],
    // 折叠展开
    toggle: false,
    //全选
    selectedAll: false,
    //当前展开节点
    expandedKeys: [],
    // 所有父节点集合
    nodeWithChidren: [],
  });

  const menuStates = reactive({
    checkedKeys: [],
    // 折叠展开
    toggle: false,
    //全选
    selectedAll: false,
    //当前展开节点
    expandedKeys: [],
    // 所有父节点集合
    nodeWithChidren: [],
  });

  const schemaFormRef = ref<any>(null);

  const getFormProps = ref({
    layout: 'horizontal',
    labelWidth: 100,
    schemas: useRoleSchema(),
    showActionButtonGroup: false,
  });
  const editDrawerBindValue = reactive({
    defaultSelectData: [],
    runType:'',
    modelType:'',
  });
  const userSingleRef = ref<FormInstance>();
  const openModal = async()=>{
    ModalRender.show({
    title: '选择直属领导',
    width: '70%',
    destroyOnClose: true,
    content: () => {
      return <userMore  ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userMore>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await userSingleRef.value?.handleSubmit();
      if (!res) return;
        console.log(res,"11111111111111");
        if(res.length>0){
                res.map((item)=>{
                    if(props.defaultData.users.filter(obj => obj.userAccount==item.NO)<=0){
                      props.defaultData.users.push({
                            userAccount:item.NO,
                            name:item.NAME,
                        }); 
                    }
                })
            }
      },
    });
  };

  // 部门权限
  const persState = reactive({
    dataScope: '2',
  });

  const [DynamicTable] = useTable({
    size: 'small',
    rowKey: 'id',
    bordered: true,
    showIndex: true,
    search: false,
    showToolBar: false,
  });

  const columns = [
    {
      title: '登录账号',
      dataIndex: 'userAccount',
      align: 'center',
    },
    {
      title: '人员姓名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '操作',
      width: 150,
      dataIndex: 'ACTION',
      align: 'center',
      actions: ({ record }) => [
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record.userAccount),
          },
        },
      ],
    },
  ];
  const delRowConfirm = async (userId: string) => {
    props.defaultData.users=props.defaultData.users.filter(obj => obj.userAccount!=userId)
  };
  // 获取所有父节点方法
  const findNodeWithChildren = (data, keyName = 'id') => {
    let keys: any = [];
    const filterFunc = (list, keyName: string) => {
      list.forEach((item: any) => {
        if (item.children && item.children.length) {
          keys.push(item[keyName]);
          filterFunc(item.children, keyName);
        }
      });
    };
    filterFunc(data, keyName);
    return keys;
  };

  watch(
    () => props.defaultData,
    (newVal) => {
      console.log(props.defaultData);
      persState.dataScope = newVal?.roleData?.data_scope ?? '2';
      menuStates.checkedKeys = newVal?.menus ?? [];
      deptsStates.checkedKeys = newVal?.depts ?? [];
      menuStates.nodeWithChidren = findNodeWithChildren(props.defaultData.menusAll, 'menuId');
      deptsStates.nodeWithChidren = findNodeWithChildren(props.defaultData.deptsAll);
    },
    {
      deep: true,
    },
  );

  watch(
    () => menuStates.selectedAll,
    (newVal) => {
      menuStates.checkedKeys = newVal ? props.defaultData.menuKeysAll : [];
    },
  );

  watch(
    () => deptsStates.selectedAll,
    (newVal) => {
      deptsStates.checkedKeys = newVal ? props.defaultData.deptsKeysAll : [];
    },
  );

  watch(
    () => menuStates.toggle,
    (newVal) => {
      menuStates.expandedKeys = newVal ? menuStates.nodeWithChidren.map((i) => i) : [];
    },
  );

  watch(
    () => deptsStates.toggle,
    (newVal) => {
      deptsStates.expandedKeys = newVal ? deptsStates.nodeWithChidren.map((i) => i) : [];
    },
  );

  const onSubMit = async () => {
    const result = await schemaFormRef.value?.validate();
    return {
      dataScope: persState.dataScope,
      depts: persState.dataScope == '2' ? deptsStates.checkedKeys : [],
      menuIds: menuStates.checkedKeys,
      users: props.defaultData.users,
      roleName: result.roleName,
      roleId: result.roleId,
      remark: result.remark,
    };
  };

  defineExpose({
    handleSubmit: onSubMit,
  });

  onMounted(() => {
    schemaFormRef.value?.setFieldsValue({
      ...props.defaultData.roleData,
    });
  });
</script>
